package com.ssdp.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ssdp.constant.PageConstant;
import com.ssdp.dto.Result;
import com.ssdp.dto.UserDTO;
import com.ssdp.entity.Blog;
import com.ssdp.service.IBlogService;
import com.ssdp.utils.UserHolder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * @author syo 2319615164@qq.com
 * @description 博客管理接口
 * @date 2024/3/14
 * @Copyright syo
 */
@RestController
@RequestMapping("/blog")
@Slf4j
@RequiredArgsConstructor
@Api(tags = "博客管理接口")
public class BlogController {

    private final IBlogService blogService;

    @ApiOperation("新增博客")
    @PostMapping
    public Result saveBlog(@RequestBody Blog blog) {
        return blogService.saveBlog(blog);
    }

    @ApiOperation("点赞和取消点赞博客")
    @PutMapping("/like/{id}")
    public Result likeBlog(@PathVariable("id") Long id) {
        return blogService.likeBlog(id);
    }

    @ApiOperation("分页查询个人博客")
    @GetMapping("/of/me")
    public Result queryMyBlog(@RequestParam(value = "current", defaultValue = "1") Integer current) {
        // 1. 获取登录用户
        UserDTO user = UserHolder.getUser();
        // 2. 根据用户查询
        Page<Blog> page = blogService.query()
                .eq("user_id", user.getId())
                .page(new Page<>(current, PageConstant.MAX_PAGE_SIZE));

        // 3. 获取当前页数据
        List<Blog> records = page.getRecords();
        return Result.ok(records);
    }

    @ApiOperation("获取热点博客")
    @GetMapping("/hot")
    public Result queryHotBlog(@RequestParam(value = "current", defaultValue = "1") Integer current) {

        return blogService.queryHotBlog(current);
    }

    @ApiOperation("根据博客Id查询博客详情")
    @GetMapping("/{id}")
    public Result queryBlogById(@PathVariable("id") Long id) {
        return blogService.queryBlogById(id);
    }

    @ApiOperation("查询博客点赞数")
    @GetMapping("/likes/{id}")
    public Result queryBlogLikes(@PathVariable("id") Long id) {
        return blogService.queryBlogLikes(id);
    }

    @ApiOperation("根据用户Id查询博客信息")
    @GetMapping("/of/user")
    public Result queryBlogByUserId(
            @RequestParam(value = "current", defaultValue = "1") Integer current,
            @RequestParam("id") Long id) {
        Page<Blog> page = blogService.query()
                .eq("user_id", id)
                .page(new Page<>(current, PageConstant.MAX_PAGE_SIZE));
        List<Blog> records = page.getRecords();
        return Result.ok(records);
    }

    @ApiOperation("获取关注用户的所有博客信息")
    @GetMapping("/of/follow")
    public Result queryBlogOfFollow(@RequestParam("lastId") Long max,
                                    @RequestParam(value = "offset", defaultValue = "0") Integer offset) {
        return blogService.queryBlogOfFollow(max, offset);
    }
}
